package com.jinwei.qunguanjia.web.monitor.controller;

import com.jinwei.qunguanjia.common.annotation.Log;
import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.core.page.PageDataInfo;
import com.jinwei.qunguanjia.common.core.redis.RedisCache;
import com.jinwei.qunguanjia.common.enums.BusinessTypeEnum;
import com.jinwei.qunguanjia.common.utils.JsonUtils;
import com.jinwei.qunguanjia.common.utils.StringUtils;
import com.jinwei.qunguanjia.common.utils.SystemContextUtils;
import com.jinwei.qunguanjia.common.utils.TenantContextUtils;
import com.jinwei.qunguanjia.system.dto.SysLoginUser;
import com.jinwei.qunguanjia.system.service.TokenService;
import com.jinwei.qunguanjia.system.utils.SecurityUtils;
import com.jinwei.qunguanjia.web.monitor.vo.SysUserOnlineVO;
import com.jinwei.qunguanjia.web.system.vo.SysUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 在线用户监控
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController {

    @Resource
    private RedisCache redisCache;

    @Resource
    private TokenService tokenService;

    @PreAuthorize("@ss.hasPermission('monitor:online:list')")
    @GetMapping("/list")
    public PageDataInfo<SysUserOnlineVO> list(String ipAddr, String userName)
    {
        Collection<String> keys = redisCache.keys(tokenService.getBackendTokenKey(SystemContextUtils.getToken()) + "*");
        List<SysUserOnlineVO> userOnlineList = new ArrayList<>();
        for (String key : keys)
        {
            SysLoginUser user = redisCache.getCacheObject(key);
            SysUserVO userInfo = JsonUtils.parseObject(Objects.requireNonNull(SecurityUtils.getLoginUser()).getUserJson(), SysUserVO.class);
            if (StringUtils.isNotEmpty(ipAddr) && StringUtils.isNotEmpty(userName))
            {
                if (StringUtils.equals(ipAddr, user.getIpAddress()) && StringUtils.equals(userName, user.getUsername()))
                {
                    SysUserOnlineVO sysUserOnlineVO = new SysUserOnlineVO();
                    BeanUtils.copyProperties(user, sysUserOnlineVO);
                    sysUserOnlineVO.setUserName(user.getUsername());
                    sysUserOnlineVO.setTokenId(user.getToken());
                    sysUserOnlineVO.setDeptName(userInfo.getDept().getDeptName());
                    userOnlineList.add(sysUserOnlineVO);
                }
            }
            else if (StringUtils.isNotEmpty(ipAddr))
            {
                if (StringUtils.equals(ipAddr, user.getIpAddress()))
                {
                    SysUserOnlineVO sysUserOnlineVO = new SysUserOnlineVO();
                    BeanUtils.copyProperties(user, sysUserOnlineVO);
                    sysUserOnlineVO.setUserName(user.getUsername());
                    sysUserOnlineVO.setTokenId(user.getToken());
                    sysUserOnlineVO.setDeptName(userInfo.getDept().getDeptName());
                    userOnlineList.add(sysUserOnlineVO);
                }
            }
            else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUserJson()))
            {
                if (StringUtils.equals(userName, user.getUsername()))
                {
                    SysUserOnlineVO sysUserOnlineVO = new SysUserOnlineVO();
                    BeanUtils.copyProperties(user, sysUserOnlineVO);
                    sysUserOnlineVO.setUserName(user.getUsername());
                    sysUserOnlineVO.setTokenId(user.getToken());
                    sysUserOnlineVO.setDeptName(userInfo.getDept().getDeptName());
                    userOnlineList.add(sysUserOnlineVO);
                }
            }
            else
            {
                SysUserOnlineVO sysUserOnlineVO = new SysUserOnlineVO();
                BeanUtils.copyProperties(user, sysUserOnlineVO);
                sysUserOnlineVO.setUserName(user.getUsername());
                sysUserOnlineVO.setTokenId(user.getToken());
                sysUserOnlineVO.setDeptName(userInfo.getDept().getDeptName());
                userOnlineList.add(sysUserOnlineVO);
            }
        }
        PageDataInfo<SysUserOnlineVO> pageDataInfo = new PageDataInfo<>();
        pageDataInfo.setData(userOnlineList);
        pageDataInfo.setTotal(userOnlineList.size());
        return pageDataInfo;
    }

    /**
     * 强退用户
     */
    @PreAuthorize("@ss.hasPermission('monitor:online:forceLogout')")
    @Log(title = "在线用户", businessType = BusinessTypeEnum.FORCE)
    @DeleteMapping("/remove")
    public Response forceLogout(String tokenId, String userName)
    {
        redisCache.deleteObject(tokenService.getBackendUserNameKey(userName));
        redisCache.deleteObject(tokenService.getBackendTokenKey(tokenId));
        return Response.success();
    }
}
